import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import React, { Component } from "react";
import Sidebar from './sidebar/sidebar';
import Header from './header/header';
import './css/admin.less';
import Home from '../home/home';
import Devices from '../devices/devices';
import Settings from '../settings/settings';
import Datas from '../date/dates';
import Construction from '../construction/construction';
import Emergency from '../emergency/emergency';
import Location from '../location/location';
import { meshLog, SPRemove, SPGet, SPSet } from "../../config";
import PubSub from 'pubsub-js';
import Mqtt from './mqtt';
import { building, mesh } from '../../api/index.js';
import axios from 'axios';
import { decryptByAes256CBC } from './jiemi';
import Delayed from './delay'
import { Layout, Button, Modal, message } from 'antd';
import { connect } from 'react-redux'
import { createDeletUserInfoAction } from '../../redux/action_craetors/login_action'
import {
  hexToNegativeDecimal
} from '../../utils/dataUtils'
const { Content } = Layout;

class Admin extends Component {

  async componentDidMount() {
    meshLog('admin渲染第一步',);
    meshLog('admin.jsx,113行,从父类传过来的所有数据', this.props);//从父类传过来的props
    //先获取building，找到isSelected为1的，拿到uuid。然后在访问mesh接口，找到加密的json，解密 SPSet("token", value.token)   SPRemove("token")
    const deviceNo = "1122334455667788"
    let token = SPGet('token')
    let maddr = SPGet('email')
    let result = await building(maddr, deviceNo, token);
    //如果build长度0，没有isSelected为1 home界面显示空
    if (result.code == 0) {
      const buildingList = result.msg.buildingList
      meshLog('所有的building', buildingList);
      if (buildingList.length == 0) {
        SPSet("buildingListLength", 0)
      } else {
        let isSelected = buildingList.find(item => item.isSelected == 1)
        if (isSelected) {
          // meshLog('isSelected', isSelected);
          const buildingUUID = isSelected.buildingUUID
          let buildingresult = await mesh(maddr, deviceNo, token, buildingUUID);
          meshLog('isSelected为1的', buildingresult);
          const meshList = buildingresult.msg.meshList
          SPSet("meshList", JSON.stringify(meshList))
          //mesh对应的area，要先判断这个mesh下有没有数据
          if (meshList.length == 0) {
            // meshLog('meshList', meshList.length);
          } else {
            //如果有，默认解密meshlist中第一个数据的poidfile
            // let dUrl
            // for (let index = 0; index < meshList.length; index++) {
            //   if (!meshList[index].profile) {
            //     dUrl = meshList[index].profile;
            //   }
            // }
            const dUrl = meshList[0].profile
            //meshLog('dUrl', dUrl);
            axios.get(dUrl)
              .then(async (value) => {
                //meshLog('admin235value', value.data);
                const hex_key = meshList[0].meshUUID + "3a8f1c7d0b9e2a4f6c5d0e1f2a3b4c5d"
                const decryptedString = decryptByAes256CBC(hex_key, value.data)
                const jsonData = JSON.parse(decryptedString);
                meshLog('jsonData', jsonData);//拿到需要解析的所有数据
                const zoneList = jsonData.zoneList
                const groupList = jsonData.groupList
                const nodes = jsonData.nodes
                let wangguan = nodes.find(item => item.pid == '4100')
                //如果没有网关，这边需要做个判断
                if (wangguan) {
                  SPSet("wangguan", JSON.stringify(wangguan))
                } else {
                  wangguan = { 'macAddress': '1234567890' }
                  SPSet("wangguan", JSON.stringify(wangguan))
                }
                meshLog('wangguan', wangguan);
                SPSet("image", JSON.stringify(meshList[0].image))
                SPSet("groupList", JSON.stringify(groupList))
                SPSet("zoneList", JSON.stringify(zoneList))
                SPSet("nodes", JSON.stringify(nodes))
                SPSet("changemeshlist", JSON.stringify(0))//判断是否在网页中手动修改过meshlist

              })
              .catch((resaon) => {
                meshLog(resaon);
              })
            //获取OTA固件版本
            const otaurl = 'https://iot.hsesmartinc.com/light/version.json'
            axios.get(otaurl)
              .then(async (value) => {
                meshLog('value', value.data);
                const firmware_version = value.data.version
                console.log('firmware_version:', firmware_version);
                SPSet("firmware_version", JSON.stringify(firmware_version))

              })
              .catch((resaon) => {
                meshLog(resaon);
              })
          }
          SPSet("buildingList", JSON.stringify(buildingList))
          SPSet("meshList", JSON.stringify(meshList))
          SPRemove("buildingListLength")
          SPSet("buildingListLength", buildingList.length)
        } else {
          SPSet("buildingListLength", 0)
        }
      }
    }




    // 成功的mqtt开始
    let mqttpandun = 0//用来进行mqtt判断，如果一直是0，就说明mqtt没收到信息，这就要修改OK弹框
    var mqtt = new Mqtt("iot.hsesmartinc.com:3100");//里面写上ip和端口
    //var mqtt = new Mqtt("44.204.237.47:3100");//里面写上正式ip和端口
    var Wed_Send = "web-gateway";//这里就是网页发的主题  测试服务器 3.19.244.79
    var gateway_web = "gateway-web";//这里就是网关主题     正式    13.218.48.143/light/version.json
    mqtt.link().then((client) => {//封装成promsie方便使用
      //client这里保留了原生的client函数和用法
      var sendMess = { //这就是要传给后端的参数
        // MessageId: topic,
        // TopicId: topic,
        // Time: new Date().getTime(),
        test: 456,//这个mqtt是生成随机生成的随机数
        //当然要想申请新的随机数可以mqtt.random()
      };
      //mqtt.subscribe(Wed_Send);//订阅主题
      mqtt.subscribe(gateway_web);//订阅主题
      // mqtt.subscribe(topic + "/" + mqtt.clientId);//订阅主题
      //mqtt.publish(topic, sendMess, { qos: 0 })//向某个主题发送消息
      // 在函数外定义，确保全局共享
      let otaTimer = null;

      mqtt.message(function (data, gateway_web) {
        meshLog("mqtt回传之后的信息1111", data);
        const versionPanduan1 = data.slice(46, 50)
        const OTAPanduan = data.slice(12, 16)
        const versionPanduan2 = data.slice(38, 40)
        const OTApid = JSON.parse(SPGet("OTApid"))
        const versionPanduan3 = data.slice(50, 54)

        if (versionPanduan3 == OTApid && versionPanduan1 == '0F00' && versionPanduan2 == '00') {
          const hexStr = data.slice(40, 42)
          const hexStrValue = hexToNegativeDecimal(hexStr)
          const OTAValue = JSON.parse(SPGet("OTAValue"))
          meshLog('OTAValue', OTAValue);
          const OTAMACValue = data.slice(12, 24)
          meshLog('OTAValueOTAMAC', OTAMACValue);
          meshLog('hexStrValue', hexStrValue);

          if (hexStrValue > OTAValue) {
            SPRemove("OTAValue")
            SPSet("OTAValue", hexStrValue)
            SPRemove("OTAMAC")
            SPSet("OTAMAC", OTAMACValue)
          }

          // ✅ 延时发布逻辑
          if (otaTimer) {
            clearTimeout(otaTimer);
            console.log(`[DEBUG] 10秒内收到新消息，清除之前定时器，重置倒计时`);
          } else {
            console.log(`[DEBUG] 第一次收到OTA消息，启动10秒定时器`);
          }

          otaTimer = setTimeout(() => {
            PubSub.publish("OTAfrist", data);
            console.log(`[DEBUG] 10秒无新消息，触发发布 OTAfrist`);
            otaTimer = null;
          }, 3000);
        }

        if (OTAPanduan == '0330') {
          meshLog('OTAPanduan', OTAPanduan);
          PubSub.publish('OTASecond', data)//直接控制OK弹框
        }
      });

      //10秒之后进行判断mqtt有没有收到信息
      setTimeout(() => {
        if (mqttpandun == 0) {
          meshLog('admin.jsx,189行,mqtt没有收到数据了');
          PubSub.publish('mqttguanbi2', '')//直接控制OK弹框
        } else {
          meshLog('admin.jsx,193行,mqt收到数据了');
          PubSub.publish('mqttguanbi', '')//直接控制OK弹框
        }
      }, 10000)
      //10秒之后进行判断mqtt有没有收到信息结束
    });
    // 成功的mqtt
    //关闭mqtt信息
    PubSub.unsubscribe("clearmqtt")
    PubSub.subscribe('clearmqtt', (msg, index) => {
      mqtt.close()
    })

    //开关灯，控灯指令，需要延迟320毫秒
    //和网关交互不需要延迟，这边需要区分
    PubSub.unsubscribe("showUpdate")
    PubSub.subscribe('showUpdate', (msg, data) => {
      meshLog('msg', data);
      setTimeout(() => {
        mqtt.publish(Wed_Send, ',' + data, { qos: 0 })//向某个主题发送消息
      }, 320)
    })

    //退出
    PubSub.unsubscribe("deletUser")
    PubSub.subscribe('deletUser', (msg, data) => {
      this.props.deletUser()
    })

  }


  render() {
    const { isLogin } = this.props.userInfo
    if (!isLogin) {
      return <Navigate replace to="/login" />
    }
    else {
      return (
        <div className='appLayout'>

          <div style={{ height: 65 }}><Header /></div>
          <div className='mainSection'>
            <div className='sidebar'>
              <Sidebar />
            </div>
            <div className='content'>
              <Routes>
                <Route path="/" element={
                  <Delayed waitBeforeShow={2000}>
                    <Home />
                  </Delayed>
                } />
                <Route path="/home" element={<Home />} />
                <Route path="/devices" element={<Devices />} />
                <Route path="/settings" element={<Settings />} />
                <Route path="/date" element={<Datas />} />
                {/* <Route path="/construction" element={<Construction />} />
                <Route path="/location" element={<Location />} /> */}
                <Route path="/emergency" element={<Emergency />} />
              </Routes>
            </div>
          </div>
        </div>
      );
    }
  }
}

export default connect(
  state => ({ userInfo: state }),
  { deletUser: createDeletUserInfoAction }
)(Admin)
